  var RSA = require('../utils/wx_rsa.js')
  const app = getApp()

var HOST = "http://192.168.2.151/wxapp/index.php/openapi/promotion_route/accept"
var Pic = 'http://192.168.2.151/wxapp/index.php/openapi/promotion_route/upload'
const DOCHTTP = 'http://192.168.2.151/wxapp/public/files/protocol.docx'  //文档地址

 const key = 'c92a54950b4c09247ec02edce69f6a2d'

const SERVERPORT = "https://ykl.etonepay.com/pos/basicSend/small_routine"

const VSERVERPORT = "https://ykl.etonepay.com/pos/basicSend/basic_bnLogin"
const NORMAL = "https://ykl.etonepay.com/pos/basicSend/"

  function httpPost(url, jsonParm, callback) {
    wx.request({
      method: 'POST',
      url: HOST,
      data: jsonParm,
      success(res) {
        var response_code = res.data ? res.data.return_code : res.return_code;
        var response_mes = res.data ? res.data.return_msg : res.return_msg;
        if (response_code == '0000') {
          callback('', res.data);
        } else {
          callback(response_mes,'');
        }
      },
      fail(e) {
        callback('请求超时')
      },
      complete: function() {
      }
    })
  }
  //post请求
  function Cpic_fetchPost(url, jsonParm, callback) {
    var merchan = app.globalData.merNo;
    var tempstr = '';
    var dic = jsonParm;
    dic['version'] = '1.0.0';
    dic['device_info'] = '';
    dic['source'] = 'weixin';
    dic['sign_type'] = 'RSA';
    dic["seller_bn"]=merchan;
    // dic['seller_id'] = merchan;

    var sdic = Object.keys(dic).sort();
    for (var ki in sdic) {
      var temp = dic[sdic[ki]];
      if (temp == ''||!temp) {
        continue;
      }
      var jsons = '';
      if (Array.isArray(temp)) {
        jsons = JSON.stringify(temp);
        tempstr += sdic[ki] + "=" + jsons + "&";
      } else {
        tempstr += sdic[ki] + "=" + temp + "&";
      }
    }
    tempstr = tempstr + 'key=' + key;
    // tempstr = tempstr.replace(/\s+/g, ""); 
    // var sign = RSA_Sign.hexMD5(tempstr);
    var sign_rsa = new RSA.RSAKey();
    sign_rsa = RSA.KEYUTIL.getKey(privateKey);
    var hashAlg = 'sha1';
    var Sig = sign_rsa.signString(tempstr, hashAlg);
    Sig = RSA.hex2b64(Sig); // hex 转 b64
    jsonParm["sign"] = Sig;
    console.log('发送post请求 url=' + url + '|' + 'jsonParm=' + JSON.stringify(jsonParm));

    wx.request({
      method: 'POST',
      url: HOST,
      // header: { 'Content-type': 'application/x-www-form-urlencoded' },
      data: jsonParm,
      success(res) {
        var response_code = res.data.return_code;
        var response = res.data;
        var cstatus = res.statusCode;
        if (cstatus == 200) {
          if (response_code != "0000") {
            var respo = response.return_msg ? response.return_msg : '返回异常'
            callback(respo, response_code);
          } else {
            var resigndata = res.data;
            var valid = resigndata.data;
            if (!valid) {
              callback("", resigndata);
              return;
            }
            var bstatus = validSign(valid, resigndata.sign);
            if (bstatus) {
              callback("", res.data);
            } else {
              callback('验签失败');
            }
          }
        } else {
          callback('网络请求异常');
        }
      },
      fail(e) {
        callback('请求超时')
      },
      complete: function() {
        wx.hideToast();
      }
    })
  }

//post请求
function htp(metd, jsonParm, callback) {
  var merchan = app.globalData.merNo;
  var tempstr = '';
  var dic = jsonParm;
  dic['version'] = '1.0.0';
  dic['device_info'] = '';
  dic['source'] = 'weixin';
  dic['sign_type'] = 'RSA';
  dic["seller_bn"] = merchan;
  dic['method'] = metd;

  var sdic = Object.keys(dic).sort();
  for (var ki in sdic) {
    var temp = dic[sdic[ki]];
    if (temp == '' || !temp) {
      continue;
    }
    var jsons = '';
    if (Array.isArray(temp)) {
      jsons = JSON.stringify(temp);
      tempstr += sdic[ki] + "=" + jsons + "&";
    } else {
      tempstr += sdic[ki] + "=" + temp + "&";
    }
  }
  tempstr = tempstr + 'key=' + key;
  // tempstr = tempstr.replace(/\s+/g, ""); 
  // var sign = RSA_Sign.hexMD5(tempstr);
  var sign_rsa = new RSA.RSAKey();
  sign_rsa = RSA.KEYUTIL.getKey(privateKey);
  var hashAlg = 'sha1';
  var Sig = sign_rsa.signString(tempstr, hashAlg);
  Sig = RSA.hex2b64(Sig); // hex 转 b64
  jsonParm["sign"] = Sig;
  console.log('发送post请求 jsonParm=' + JSON.stringify(jsonParm));

  wx.request({
    method: 'POST',
    url: HOST,
    // header: { 'Content-type': 'application/x-www-form-urlencoded' },
    data: jsonParm,
    success(res) {
      var response_code = res.data.return_code;
      var response = res.data;
      var cstatus = res.statusCode;
      if (cstatus == 200) {
        if (response_code != "0000") {
          var respo = response.return_msg ? response.return_msg : '返回异常'
          callback(respo, response_code);
        } else {
          var resigndata = res.data;
          var valid = resigndata.data;
          if (!valid) {
            callback("", resigndata);
            return;
          }
          var bstatus = validSign(valid, resigndata.sign);
          if (bstatus) {
            callback("", res.data);
          } else {
            callback('验签失败');
          }
        }
      } else {
        callback('网络请求异常');
      }
    },
    fail(e) {
      callback('请求超时')
    },
    complete: function () {
      wx.hideToast();
    }
  })
}


  function validSign(data, sign) {
    var dic = data
    var sdic = Object.keys(dic).sort();
    var tempstr = '';
    for (var ki in sdic) {
      var temp = dic[sdic[ki]];
      if (temp == '') {
        continue;
      }
      var jsons = '';
      if (Array.isArray(temp) || temp.constructor == Object) {
        jsons = JSON.stringify(temp);
        tempstr += sdic[ki] + "=" + jsons + "&";
      } else {
        tempstr += sdic[ki] + "=" + temp + "&";
      }
    }
    if (tempstr == '') return true;
    tempstr = tempstr + 'key=' + key;
    // tempstr = tempstr.replace(/\s+/g, ""); 

    var verify_rsa = new RSA.RSAKey();
    verify_rsa = RSA.KEYUTIL.getKey(publicKey);
    var Sig = RSA.b64tohex(sign);
    var ver = verify_rsa.verifyString(tempstr, Sig)
    console.log('验签结果：' + ver)
    return ver;
  }

  module.exports = {
    Cpic_fetchPost: Cpic_fetchPost,
    SERVERPORT: SERVERPORT,
    httpPost: httpPost,
    VSERVERPORT: VSERVERPORT,
    htp: htp,
    SHOST:HOST,
    PHOST: Pic,
    DOCHTTP: DOCHTTP,
  }

  var privateKey = '-----BEGIN RSA PRIVATE KEY-----MIICWwIBAAKBgQDkHfJU25PxBDP2fA/AkQTUkmLdU9JHjPydlR1tDZLCU9VWagnxTY46jT9gv6ral/i+xPq3wGmj1Hpaajh6mDWYBD84psOUIRNQ9RdcuAkH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